package com.h3c.ptability.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.h3c.ptability.client.SapClient;
import com.h3c.ptability.entity.PtEnum;
import com.h3c.ptability.mapper.PtEnumMapper;
import com.h3c.ptability.utils.AppBusinessException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class SapService {

    @Autowired
    SapClient sapClient;

    @Autowired
    CommService commService;

    @Autowired
    PtEnumMapper ptEnumMapper;

    @Value("${hrss.nem.account}")
    private String appId;

    @Value("${hrss.nem.secret}")
    private String appSecret;

    @Value("${hrss.nem.password}")
    private String curSecret;

    public Object getSapDataItems(){
        String sapToken = commService.getSapToken(appId, appSecret);
        try {
            JSONObject result = sapClient.getSapDataItems(sapToken);
            return result.get("data");
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("获取SAP数据项失败");
        }
    }

    @Data
    public static class Codes{
        private String keyValue;
        private String keyText;
        private String keyName;
    }

    @Data
    public static class EducationDegreeMaps{
        private String education;
        private String educationCode;
        private String degree;
        private String degreeCode;
    }

    @Data
    public static class PersonalRanges{
        private String personalRangeName;
        private String personalRangeCode;
    }

    @Data
    public static class PersonalSecRanges{
        private String personalRangeSecName;
        private String personalRangeSecCode;
        private String personalRangeCode;
    }

    @Data
    public static class SapData{
        @JSONField(name="outputtingCodes")
        private Set<Codes> outputtingCodesList;
        @JSONField(name="workPlaceCodes")
        private Set<Codes> workPlaceCodesList;
        @JSONField(name="nationality")
        private Set<Codes> nationalityList;
        @JSONField(name="educationDegreeMaps")
        private Set<EducationDegreeMaps> educationDegreeMapsList;
        @JSONField(name="personalRanges")
        private Set<PersonalRanges> personalRangesList;
        @JSONField(name="personalSecRanges")
        private Set<PersonalSecRanges> personalSecRangesList;
        @JSONField(name="notWorkDays")
        private Set<Codes> notWorkDaysList;
    }

    public void saveSap(){
        Object sapDataItems = getSapDataItems();
        PtEnum ptEnum;
        String data = JSONObject.toJSONString(sapDataItems);
        SapData sapData = JSONObject.parseObject(data, SapData.class);
        Set<Codes> outputtingCodesList = sapData.getOutputtingCodesList();
        for (Codes codes : outputtingCodesList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_OUTPUTTINGCODES");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("外派工作地");
            if (!StringUtils.hasText(codes.getKeyValue()) || !StringUtils.hasText(codes.getKeyText())){
                continue;
            }else{
                ptEnum.setValue(codes.getKeyValue());
                ptEnum.setNameZh(codes.getKeyText());
            }
            queryAndInsertPtEnum(ptEnum, codes);
        }
        Set<Codes> workPlaceCodesList = sapData.getWorkPlaceCodesList();
        for (Codes codes : workPlaceCodesList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_WORKPLACECODES");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("工作履行地");
            if (!StringUtils.hasText(codes.getKeyValue()) || !StringUtils.hasText(codes.getKeyText())){
                continue;
            }else{
                ptEnum.setValue(codes.getKeyValue());
                ptEnum.setNameZh(codes.getKeyText());
            }
            queryAndInsertPtEnum(ptEnum, codes);
        }
        Set<Codes> nationalityList = sapData.getNationalityList();
        for (Codes codes : nationalityList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_NATIONALITY");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("国籍");
            if (!StringUtils.hasText(codes.getKeyValue()) || !StringUtils.hasText(codes.getKeyText())){
                continue;
            }else{
                ptEnum.setValue(codes.getKeyValue());
                ptEnum.setNameZh(codes.getKeyText());
            }
            queryAndInsertPtEnum(ptEnum, codes);
        }

//        Set<EducationDegreeMaps> educationDegreeMapsList = sapData.getEducationDegreeMapsList();
//        Map<String, String> map = new HashMap<String, String>();
//        for (EducationDegreeMaps educationDegreeMaps : educationDegreeMapsList) {
//            ptEnum = new PtEnum();
//            ptEnum.setEnumCode("NEW_STAFF_DEGREES");
//            ptEnum.setAppId("nem-manager");
//            ptEnum.setEnumName("学位");
//            if (!StringUtils.hasText(educationDegreeMaps.getDegreeCode()) || !StringUtils.hasText(educationDegreeMaps.getDegree())){
//                continue;
//            }else{
//                ptEnum.setValue(educationDegreeMaps.getDegreeCode());
//                ptEnum.setNameZh(educationDegreeMaps.getDegree());
//            }
//            QueryWrapper<PtEnum> enumWrapper = Wrappers.query();
//            enumWrapper.eq("app_id", ptEnum.getAppId())
//                    .eq("enum_code", ptEnum.getEnumCode())
//                    .eq("value", educationDegreeMaps.getDegreeCode());
//            PtEnum degree = ptEnumMapper.selectOne(enumWrapper);
//            if (degree != null) {
//                ptEnumMapper.deletePtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
//            }
//            ptEnumMapper.insertPtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
//            if (map.get(educationDegreeMaps.getEducationCode()) == null){
//                map.put(educationDegreeMaps.getEducationCode(), educationDegreeMaps.getDegreeCode());
//            }else{
//                String str = map.get(educationDegreeMaps.getEducationCode());
//                if (!str.contains(educationDegreeMaps.getDegreeCode())) {
//                    str = str + ',' + educationDegreeMaps.getDegreeCode();
//                    map.put(educationDegreeMaps.getEducationCode(), str);
//                }
//            }
//        }
//
//        for (EducationDegreeMaps educationDegreeMaps : educationDegreeMapsList) {
//            ptEnum = new PtEnum();
//            ptEnum.setEnumCode("NEW_STAFF_EDUCATION");
//            ptEnum.setAppId("nem-manager");
//            ptEnum.setEnumName("学历");
//            ptEnum.setEnumRemark(map.get(educationDegreeMaps.getEducationCode()));
//            if (!StringUtils.hasText(educationDegreeMaps.getEducationCode()) || !StringUtils.hasText(educationDegreeMaps.getEducation())){
//                continue;
//            }else{
//                ptEnum.setValue(educationDegreeMaps.getEducationCode());
//                ptEnum.setNameZh(educationDegreeMaps.getEducation());
//            }
//            QueryWrapper<PtEnum> enumWrapper = Wrappers.query();
//            enumWrapper.eq("app_id", ptEnum.getAppId())
//                    .eq("enum_code", ptEnum.getEnumCode())
//                    .eq("value", educationDegreeMaps.getEducationCode());
//            PtEnum education = ptEnumMapper.selectOne(enumWrapper);
//            if (education != null) {
//                ptEnumMapper.deletePtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
//            }
//            ptEnumMapper.insertPtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
//        }

        Set<PersonalRanges> personalRangesList = sapData.getPersonalRangesList();
        for (PersonalRanges personalRanges : personalRangesList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_PERSONALRANGENAME");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("人事范围");
            if (!StringUtils.hasText(personalRanges.getPersonalRangeCode()) || !StringUtils.hasText(personalRanges.getPersonalRangeName())){
                continue;
            }else{
                ptEnum.setValue(personalRanges.getPersonalRangeCode());
                ptEnum.setNameZh(personalRanges.getPersonalRangeName());
            }
            QueryWrapper<PtEnum> enumWrapper = Wrappers.query();
            enumWrapper.eq("app_id", ptEnum.getAppId())
                    .eq("enum_code", ptEnum.getEnumCode())
                    .eq("value", personalRanges.getPersonalRangeCode());
            PtEnum personalRange = ptEnumMapper.selectOne(enumWrapper);
            if (personalRange != null) {
                ptEnumMapper.deletePtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
            }
            ptEnumMapper.insertPtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
        }

        Set<PersonalSecRanges> personalSecRangesList = sapData.getPersonalSecRangesList();
        for (PersonalSecRanges personalSecRanges : personalSecRangesList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_PERSONALSECRANGES");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("人事子范围");
            if (!StringUtils.hasText(personalSecRanges.getPersonalRangeSecCode()) || !StringUtils.hasText(personalSecRanges.getPersonalRangeSecName())){
                continue;
            }else{
                ptEnum.setValue(personalSecRanges.getPersonalRangeSecCode());
                ptEnum.setNameZh(personalSecRanges.getPersonalRangeSecName());
            }
            ptEnum.setEnumRemark(personalSecRanges.getPersonalRangeCode());
            QueryWrapper<PtEnum> enumWrapper = Wrappers.query();
            enumWrapper.eq("app_id", ptEnum.getAppId())
                    .eq("enum_code", ptEnum.getEnumCode())
                    .eq("value", personalSecRanges.getPersonalRangeSecCode());
            PtEnum personalSecRange = ptEnumMapper.selectOne(enumWrapper);
            if (personalSecRange != null) {
                ptEnumMapper.deletePtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
            }
            ptEnumMapper.insertPtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
        }

        Set<Codes> notWorkDaysList = sapData.getNotWorkDaysList();
        for (Codes codes : notWorkDaysList) {
            ptEnum = new PtEnum();
            ptEnum.setEnumCode("NEW_STAFF_NOTWORKDAYS");
            ptEnum.setAppId("nem-manager");
            ptEnum.setEnumName("非工作日");
            if (codes.getKeyValue() == null || codes.getKeyValue().equals("")){
                continue;
            }else{
                ptEnum.setValue(codes.getKeyValue());
            }
            ptEnum.setNameZh(codes.getKeyText());
            queryAndInsertPtEnum(ptEnum, codes);
        }
    }

    private void queryAndInsertPtEnum(PtEnum ptEnum, Codes codes) {
        QueryWrapper<PtEnum> enumWrapper = Wrappers.query();
        enumWrapper.eq("app_id", ptEnum.getAppId())
                .eq("enum_code", ptEnum.getEnumCode())
                .eq("value", codes.getKeyValue());
        PtEnum ptEnum1 = ptEnumMapper.selectOne(enumWrapper);
        if (ptEnum1 != null) {
            ptEnum.setNameEn(ptEnum1.getNameEn());
            ptEnum.setEnumRemark(ptEnum1.getEnumRemark());
            ptEnumMapper.deletePtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
        }
        ptEnumMapper.insertPtEnum(JSONObject.parseObject(JSON.toJSONString(ptEnum), PtEnum.class));
    }
}
